#!/usr/bin/env python
# coding: utf-8

# Create your views here.
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
from django.db import IntegrityError

from orgcontrol.orgauth.authfuncs import get_user_profile #, get_network_admin, get_structure_admin
from orgcontrol.orgauth.authfuncs import auth_user_required #, network_admin_required, structure_admin_required
from orgcontrol.main.utils import mToInt, days_in_month
from orgcontrol.main.views import get_default_context
from orgcontrol.main.vars import PROD_POSITIONS, PROD_POSITIONS_DICT, MONTHS, MONTHS_DICT, YEARS, PRODUCTION_TYPES, PRODUCTION_TYPES_DICT

from models import ProdVolume
import datetime

@auth_user_required
def prodinf_data(request, *args, **kwargs):
    c = get_default_context(request)

    # messages.info(request, 'Three credits remain in your account.')
    # messages.success(request, 'Profile details updated.')
    # messages.warning(request, 'Your account expires in three days.')
    # messages.error(request, 'Document deleted.')

    prod_position = kwargs.get('prod_position', None)
    if prod_position is None or prod_position not in PROD_POSITIONS_DICT.keys(): return HttpResponseRedirect('/')
    c['title'] = u'Оперативные сведения'
    c['subtitle'] = PROD_POSITIONS_DICT[prod_position]
    date_str = request.GET.get('date', None)
    month_num = mToInt( request.GET.get('m', None) )
    year = mToInt( request.GET.get('y', None) )
    date = None
    if date_str:
        try: 
            date = datetime.date(*[mToInt(one) for one in date_str.split('.')[::-1] ])
            month_num = date.month
            year = date.year
        except: pass

    if not date: date = datetime.date.today()
    if month_num not in MONTHS_DICT.keys(): month_num = datetime.date.today().month
    if year not in YEARS: year = datetime.date.today().year
    date = datetime.date(year, month_num, date.day)
    c['month_name'] = MONTHS_DICT[month_num]
    c['year'] = year
    c['PRODUCTION_TYPES'] = PRODUCTION_TYPES

    if request.method == 'POST':
        index = mToInt(request.POST.get('index'))
        volume = mToInt(request.POST.get('volume'))
        #messages.debug(request, u'Сохранение: {0} индекс {1} объем {2}'.format(date, index, volume))
        if not PRODUCTION_TYPES_DICT.has_key(index): index = None

        if date and index and volume is not None:
            try:
                prod_volume = ProdVolume(user=request.user, position=prod_position, index=index, volume=volume, date=date)
                prod_volume.save()
                messages.success(request, u'Данные {0} {1} {2} успешно сохранены'.format(
                    date.strftime('%d.%m.%Y'), PRODUCTION_TYPES_DICT[index], volume
                    ))
            except IntegrityError:
                prod_volume = ProdVolume.objects.get(position=prod_position, index=index, date=date)
                old_volume = prod_volume.volume
                prod_volume.volume = volume
                prod_volume.save()
                messages.success(request, u'Данные {0} {1} успешно исправлены с {2} на {3}'.format(
                    date.strftime('%d.%m.%Y'), PRODUCTION_TYPES_DICT[index], old_volume, volume
                    ))
            except Exception as e:
                # raise e
                messages.error(request, u'Ошибка записи в БД: {0}'.format(str(e) ) )
        else:
            if not date: messages.error(request, u'Не правильно указана дата')
            if not index: messages.error(request, u'Не правильно указан продукт')
            if not volume: messages.error(request, u'Не правильно указан объем')

    data = ProdVolume(position = prod_position).get_by_month(month_num, year)
    c['data'] = {}
    c['totals'] = [0 for one in PRODUCTION_TYPES]
    total = 0
    for day in data.keys():
        c['data'][day] = []
        row_sum = 0
        for i, index in enumerate(data[day].keys()):
            row_sum += data[day][index]
            value = data[day][index]
            total += value
            c['data'][day].append(value)
            c['totals'][i] += value
        c['data'][day].append(row_sum)

    c['totals'].append(total)
    c['date'] = date.strftime("%d.%m.%Y")
    c['day'] = date.day
    c['MONTHS'] = MONTHS
    c['YEARS'] = YEARS
    return render_to_response('prodinf/data.html', c)

@auth_user_required
def prodinf_report(request, *args, **kwargs):
    c = get_default_context(request)
    c['title'] = u'Производство по годам'

    report = {}
    for year in YEARS:
        report[year] = {}
        for prod_position in PROD_POSITIONS_DICT.keys():
            data = ProdVolume(position = prod_position).get_by_year(year)
            report[year][prod_position] = {}
            for month, value in data.iteritems():
                report[year][prod_position][month] = value
    c['report'] = report
    c['MONTHS'] = MONTHS
    c['PROD_POSITIONS_DICT'] = PROD_POSITIONS_DICT
    return render_to_response('prodinf/report.html', c)
